﻿namespace GameFrameWork
{
    public partial class UIReuseContainer
    {
        readonly int dataIndex;

        readonly IUIReuseItemCtrl ctrl;

        readonly UIReuseList reuselist;

        public UIReuseItem View;
        public IUIReuseItemCtrl Ctrl => ctrl;

        public bool IsOccupied => View != null;

        public UIReuseContainer(int dataIndex, UIReuseList reuselist, IUIReuseItemCtrl ctrl, IResModule resModule)
        {
            this.dataIndex = dataIndex;
            this.reuselist = reuselist;
            this.ctrl = ctrl;
            this.ctrl.index = dataIndex;
            this.ctrl.resModule = resModule;
            this.ctrl.userDataGetter = reuselist;
        }

        public void Enable()
        {
            if (IsOccupied)
            {
                View.OnSelect = OnItemClick;
                if (ctrl is IUIReuseItemBinder binder) binder.Binding(View);
                ctrl.isSelected = reuselist.IsSelected(dataIndex);
                ctrl.rectTransform = View.RectTransform;
                ctrl.Enable();
            }
        }

        public void Disable()
        {
            if (IsOccupied)
            {
                ctrl.Disable();
                ctrl.isSelected = false;
                ctrl.rectTransform = null;
            }
        }

        public void Refresh()
        {
            if (IsOccupied)
            {
                View.name = dataIndex.ToString();
                ctrl.isSelected = reuselist.IsSelected(dataIndex);
                ctrl.rectTransform = View.RectTransform;
                ctrl.Refresh();
            }
        }

        void OnItemClick()
        {
            if (IsOccupied)
            {
                reuselist.OnItemClick(dataIndex);
            }
        }
    }
}


